import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

export const useRandomFoodStore = defineStore(
  'randomFood',
  () => {
    // 1. 初始化时从本地存储加载数据
    const loadFromStorage = () => {
      try {
        const stored = uni.getStorageSync('random-food-list')
        return stored ? JSON.parse(stored) : []
      } catch (e) {
        console.error('加载食物列表失败:', e)
        return []
      }
    }

    // 2. 定义列表并从本地加载初始值
    const foodList = ref(loadFromStorage())

    // 3. 监听列表变化，自动同步到本地存储
    watch(
      foodList,
      (newList) => {
        try {
          uni.setStorageSync('random-food-list', JSON.stringify(newList))
        } catch (e) {
          console.error('保存食物列表失败:', e)
        }
      },
      { deep: true } // 深度监听对象变化
    )

    // 4. 列表操作方法
    const addFoodToList = (food) => {
      // 避免重复添加
      if (!foodList.value.some(item => item.id === food.id)) {
        foodList.value.push({ ...food }) // 浅拷贝确保响应式
      }
    }

    const removeFoodFromList = (foodId) => {
      foodList.value = foodList.value.filter(item => item.id !== foodId)
    }

    const clearFoodList = () => {
      foodList.value = []
    }

    return {
      foodList,
      addFoodToList,
      removeFoodFromList,
      clearFoodList
    }
  }
)